<template>
  <div>
    <!-- 面包屑组件 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 卡片搜索框头部区域 -->
      <el-row :gutter="20">
        <el-col :span="9">
          <div>
            <el-input
              :placeholder="'请输入内容' /*下面可以绑定v-model*/"
              v-model="queryInfo.query"
              clearable
              @clear="getUserList()"
              class="input-with-select"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUserList()"
              ></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="addUserVisible = true"
            >添加用户</el-button
          ></el-col
        >
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" style="width: 100%" border fit>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <!-- 状态 -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              @change="changeStatus(scope.row)"
              v-model="scope.row.mg_state"
            >
            </el-switch>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-row>
              <el-button
                type="primary"
                icon="el-icon-edit"
                round
                size="mini"
                @click="editTheUser(scope.row) /*将该条数据传递过去，便于展示*/"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                round
                size="mini"
                @click="deleteTheUser(scope.row)"
              ></el-button>

              <el-tooltip
                class="item"
                effect="dark"
                content="权限管理"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-star-off"
                  round
                  size="mini"
                  @click="setUserRole(scope.row)"
                ></el-button>
              </el-tooltip>
            </el-row>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum /*当前页码*/"
        :page-sizes="[1, 2, 5, 10] /*可供选择的单页显示数量*/"
        :page-size="queryInfo.pagesize /*单页显示数量*/"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total /*总共条数*/"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户功能 平时隐藏 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserVisible /*控制添加用户对话框显示的bool值*/"
      width="50%"
    >
      <span>
        <!-- 添加用户的表单区域 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="80px"
          id="addForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户信息功能 平时隐藏 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editUserVisible /*修改用户对话框显示的bool值*/"
      width="50%"
    >
      <span>
        <!-- 添加用户的表单区域 -->
        <el-form
          :model="editForm"
          :rules="addFormRules /*这个规则和添加用户是一样的，就不再写一次了*/"
          ref="editFormRef"
          label-width="80px"
          id="addForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配用户角色功能 平时隐藏 -->
    <el-dialog
      title="分配用户角色"
      :visible.sync="isSetUserRoleVisible /*控制添加用户对话框显示的bool值*/"
      width="50%"
    >
      <span>
        <!-- 主体区域 -->
        <el-row type="flex" justify="">
          当前的用户:{{ NowHandleUser.username }}
        </el-row>
        <br />
        <el-row type="flex" justify="">
          当前的角色:{{ NowHandleUser.role_name }}
        </el-row>
        <br />
        <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isSetUserRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUserRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //用于存放用户列表数据
      userList: [],
      //用于存放get请求参数
      queryInfo: {
        // 查询参数 可以为空
        query: "",
        // 当前页码 不能为空
        pagenum: 1,
        // 每页显示条数 不能为空
        pagesize: 2,
      },
      //用户总页数
      total: 0,
      //控制添加用户对话框是否显示的bool值
      addUserVisible: false,
      //存放 添加用户表单的数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //存放 添加用户表单的验证规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "限制用户名长度为3-10", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 16, message: "限制密码长度为6-16", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: "请输入正确的电子邮箱",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: "目前只支持中国大陆手机号码",
            trigger: "blur",
          },
        ],
      },
      //控制修改用户信息对话框是否显示的bool值
      editUserVisible: false,
      //修改 添加用户表单的数据
      editForm: {
        username: "",
        email: "",
        mobile: "",
      },
      //控制分配用于角色的显示与隐藏
      isSetUserRoleVisible: false,
      //存放当前正要分配角色的用户
      NowHandleUser: {},
      //存放所有角色列表
      rolesList: {},
      //存放用户要选择的角色id
      selectRoleId: "",
    };
  },
  created() {
    //调用获取用户列表的函数
    this.getUserList();
    //调用获取角色列表的函数
    this.getRolesList();
  },
  methods: {
    //更新角色列表的函数
    async getRolesList() {
      //发送请求获取角色列表数据;
      const { data: res } = await this.$http.get(`roles`);
      console.log(res);
      if (res.meta.status == 200) {
        //获取权限列表成功
        this.rolesList = res.data;
      } else {
        this.$message.error("获取角色列表失败");
      }
    },
    //获取并保存用户列表的函数
    async getUserList() {
      const { data: ret } = await this.$http.get(`users`, {
        params: this.queryInfo,
      });
      if (ret.meta.status != 200) {
        console.log("获取用户列表失败");
      } else {
        console.log(ret);
        this.userList = ret.data.users;
        this.total = ret.data.total;
      }
    },
    //每页显示条数改变触发
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      //更新数据 并重新发送请求
      this.queryInfo.pagesize = val;
      this.getUserList();
    },
    //当前页改变触发
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      //更新数据 并重新发送请求
      this.queryInfo.pagenum = val;
      this.getUserList();
    },
    //修改用户状态的方法
    async changeStatus(val) {
      // console.log(val);
      //获取最新用户状态后发送请求
      const { data: res } = await this.$http.put(
        `users/${val.id}/state/${val.mg_state}`
      );
      if (res.meta.status != 200) {
        //修改状态失败
        this.$message.error("修改状态失败");
        val.mg_state = !val.mg_state; //重新返回原来状态
        return;
      } else {
        //修改状态成功
        this.$message.success("修改状态成功");
      }
    },
    //什么都没有的函数，用来占位
    zhanwei() {},
    //对添加用户表单进行验证 并发送请求
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          //如果表单验证不正确
          // console.log(valid);
          this.$message.error("添加失败");
        } else {
          //表单验证正确，开始发送请求
          var { data: res } = await this.$http.post(`users`, this.addForm);
          if (res.meta.status == 201) {
            //添加成功
            this.$message.success("添加成功");
            //隐藏对话框
            this.addUserVisible = false;
            //刷新用户列表
            this.getUserList();
          } else {
            this.$message.error("添加失败,请检查网络");
          }
        }
      });
    },
    //弹出修改表单对话框 并且将要修改的原信息添加到表单中
    editTheUser(data) {
      console.log(data);
      //获取要操作的用户的id
      this.NowHandleUser = data;
      //弹出对话框
      this.editUserVisible = true;
      //将要修改的原信息添加到表单中
      this.editForm.username = data.username;
      this.editForm.email = data.email;
      this.editForm.mobile = data.mobile;
    },
    //对修改用户信息表单进行验证 并发送请求
    editUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          //如果表单验证不正确
          // console.log(valid);
          this.$message.error("修改失败");
        } else {
          //表单验证正确，开始发送请求
          var { data: res } = await this.$http.put(
            `users/${this.NowHandleUser.id}`,
            this.editForm
          );
          if (res.meta.status == 200) {
            //修改成功
            this.$message.success("修改成功");
            //隐藏修改用户对话框
            this.editUserVisible = false;
            //刷新用户列表
            this.getUserList();
          } else {
            this.$message.error("添加失败,请检查网络");
          }
        }
      });
    },
    //删除用户时候弹出对话框询问
    deleteTheUser(data) {
      console.log(data);
      //保存用户正在操作的id
      this.NowHandleUser = data;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //用户点击了确定
          const { data: res } = await this.$http.delete(
            `users/${this.NowHandleUser.id}`
          );
          if (res.meta.status == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //重新读取用户列表
            this.getUserList();
          } else {
            this.$message.error("删除失败，请检查网络");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //点击按钮显示分配用户角色对话框，并保存当前正在分配角色的用户
    setUserRole(user) {
      console.log(user);
      //保存当前正在分配角色的用户
      this.NowHandleUser = user;
      this.isSetUserRoleVisible = true;
    },
    //提交分配用户角色功能
    async submitUserRole() {
      console.log(this.selectRoleId);
      console.log(this.NowHandleUser.id);
      // 发送请求了
      const { data: res } = await this.$http.put(
        `users/${this.NowHandleUser.id}/role`,
        {
          rid: this.selectRoleId,
        }
      );
      if (res.meta.status == 200) {
        //重新分配角色成功了(
        this.$message.success("分配成功");
        //成功后重置一些操作
        this.isSetUserRoleVisible = false;
        this.getUserList();
      } else {
        this.$message.error("分配失败，请检查网络设置");
      }
    },
  },
  watch: {
    //监听添加用户对话框是否关闭了  关闭了就清空表单
    addUserVisible: function (newVal, oldVal) {
      if (newVal == false && oldVal == true) {
        this.$refs.addFormRef.resetFields();
      }
    },
    //监听修改用户信息对话框是否关闭了  关闭了就清空表单
    editUserVisible: function (newVal, oldVal) {
      if (newVal == false && oldVal == true) {
        //这里用了个定时器，防止关闭时候突然闪动变成原来的信息
        setTimeout(() => {
          this.$refs.editFormRef.resetFields();
        }, 100);
      }
    },
  },
};
</script>

<style lang="less" scoped>
</style>